var mainCallPhone = "";
var targetCallPhone = localStorage.getItem("targetCallPhone");
var isCanCall = true;
var searchParam = null;//用于存表单查询的条件参数
var freeswitchIframe; //用于freeswitch挂断时停止计时
loadVersion();

function loadVersion() {
//检测是否可外呼
    if (!((/chrome\/(\d+)/.test(navigator.appVersion.toLowerCase())) && RegExp.$1 >= 29)) {
        /*layer.msg("您当前使用的浏览器版本无法进行云呼操作", {icon: 5});*/
        isCanCall = false;
    }
}

var reloadTable = null;

layui.use(['form','layer','laydate','table','laytpl','element'],function(){
    var element = layui.element;
    var laydate = layui.laydate;
    //日期
    function getNowFormatDate() {
        var date = new Date();
        var month = date.getMonth() + 1;
        var strDate = date.getDate();
        var hours = date.getHours();
        var minutes = date.getMinutes();
        var seconds = date.getSeconds();
        if (month >= 1 && month <= 9) {
            month = "0" + month;
        }
        if (strDate >= 0 && strDate <= 9) {
            strDate = "0" + strDate;
        }
        if (hours >= 0 && hours <= 9) {
            hours = "0" + hours;
        }
        if (minutes >= 0 && minutes <= 9) {
            minutes = "0" + minutes;
        }
        if (seconds >= 0 && seconds <= 9) {
            seconds = "0" + seconds;
        }
        var currentdate = "'"+date.getFullYear() + "-" + month + "-" + strDate
            + " " + hours + ":" + minutes + ":" + seconds+"'";
        return currentdate;
    }
    var getNowFormatDate = getNowFormatDate();
    var dateMin = laydate.render({
        elem: '#regDateMin',
        type: 'datetime',
        min:"1970-01-01",//设置min默认最小值
        max:getNowFormatDate,//设置一个默认最大值
        done: function (value, dates) {
            dateMax.config.min ={
                year:dates.year,
                month:dates.month-1, //关键
                date: dates.date,
                hours: 0,
                minutes: 0,
                seconds : 0
            };
        }
    });
    var dateMax = laydate.render({
        elem: '#regDateMax',
        type: 'datetime',
        min:"1970-01-01",//设置min默认最小值
        max:getNowFormatDate,
        done:function (value,dates) {
            dateMin.config.max={
                year:dates.year,
                month:dates.month-1,//关键
                date: dates.date,
                hours: 0,
                minutes: 0,
                seconds : 0
            }
        }
    });
    var form = layui.form,
        layer = layui.layer,
        $ = layui.jquery,
        laytpl = layui.laytpl,
        table = layui.table;

    var index = layer.msg('正在加载数据，请稍候',{icon: 16,time:false,shade:0.8});
    var tableIns = table.render({
        id:"id",
        elem: '#callTaskList',
        url : baseUrl+'/linkageCall/queryCallTasks',
        cellMinWidth : 95,
        page : true,
        height : "full-175",
        request: {
            pageName: 'page' //页码的参数名称，默认：page
            ,limitName: 'pageSize' //每页数据量的参数名，默认：limit
        },response: {
            statusName: 'code' //数据状态的字段名称，默认：code
            ,statusCode: 1 //成功的状态码，默认：0
            ,msgName: 'msg' //状态信息的字段名称，默认：msg
            ,countName: 'total' //数据总数的字段名称，默认：count
            ,dataName: 'records' //数据列表的字段名称，默认：data
        },loading: true
        ,where:{doSearch:$("#doSearch").val()}
        ,page: {
            limit: 10
            ,limits: [10, 20, 30, 40, 50]
            ,curr: 1
            ,groups: 5
            ,theme: '#5FB878'
            ,first: '首页'
            ,last: '尾页'
            ,prev: '<em><i class="layui-icon">&#xe603;</i></em>'
            ,next: '<em><i class="layui-icon">&#xe602;</i></em>'
            ,layout: [ 'prev', 'page', 'next', 'skip','count']
        },
        cols : [[
            {field: 'taskName', title: '资料包名称',width:'20%',minWidth:150},
            {field: 'packageName', title: '话术包',width:'15%',minWidth:150},
            {title: '进度',width:'15%',minWidth:110, align:'center', valign:"middle",templet:"#newsStatus",templet:function (d) {
                var percent = d.takePhoneNum + "/" + d.callNum;
                return percent;
            }},
            {field: 'createUserName', title: '创建人',width:'15%',minWidth:110, align:'center'},
            {field: 'createTime', title: '创建时间', align:'center', width:'15%',minWidth:150},
            {title: '操作', width:'20%',minWidth:190, templet:'#newsListBar',fixed:"right",align:"center"}
        ]],done: function(res, curr, count){
            intTableColorChange();
            layer.close(index) //加载完数据
        }
        ,text: {
            none: "false"==$("#doSearch").val()?'':'暂无相关数据' //默认：无数据。注：该属性为 layui 2.2.5 开始新增
        }
    });

    //重新加载table的数据
    reloadTable = function () {
        var load = layer.load();
        var whereParam = {};
        if(searchParam!=null){
            whereParam = searchParam;
        }
        whereParam["doSearch"] = "true";
        tableIns.reload({
            page: {
                curr: 1 //重新从第 1 页开始
            }
            ,where: whereParam
        });
        layer.close(load);
    };

    //搜索【此功能需要后台配合，所以暂时没有动态效果演示】


    // 提交查询条件表单
    form.on('submit(query)', function(data){
        searchParam = data.field;
        reloadTable();
    });

    function toFreeswitchCall(data) {
        if(isCanCall == true){
            if(data.status == 'FINISHED'){
                layer.msg("任务包已call完");
                return;
            }
            if(targetCallPhone == "" || targetCallPhone==null ||  targetCallPhone.toUpperCase()=="NULL"){
                layer.msg("请先设置call客号码，再进行外呼操作!");
                return;
            }else{
                var regTxt =/^([0-9]{3,4}-)?[0-9]{7,8}$/ ;
                var regTelPhoneTxt =/^(((13[0-9]{1})|(15[0-9]{1})|(18[0-9]{1}))+\d{8})$/;
                if(targetCallPhone!="" && !regTxt.test(targetCallPhone) && !regTelPhoneTxt.test(targetCallPhone)){
                    layer.msg("请先设置正确的call客号码，再进行外呼操作!");
                    return;
                }
            }
            var params = "mainCallPhone="+mainCallPhone+"&targetCallPhone="+targetCallPhone+"&taskId="+data.id+"&aiCall=false&freeswitchCall=true";
            console.log(params);
            var fsCallWin = layer.open({
                title : "fwCall客",
                closeBtn:0,
                type : 2,
                content : [baseUrl+"/linkageCall/callDetail?"+params],
                resize:true,
                maxmin:false,
                isOutAnim:true,
                scrollbar:true,
                area: ['85%', '93%']/*,
                success:function (layero, index) {
                     freeswitchIframe = window[layero.find('iframe')[0]['name']];
                },
                btn: ['关闭窗体']
                , yes: function (index, layero) {
                    var body = layer.getChildFrame('body', index); //得到子页面层的BODY
                    var button = body.find('#closeWin'); //获取子窗口表单提交按钮dom
                    button.click();
                }*/
            });
            layui.layer.full(fsCallWin);
        }else{
            layer.msg("您当前使用的浏览器版本无法进行云呼操作", {icon: 5});
            return;
        }

    }


    function addTasks(edit){
         layer.open({
            title : "创建云呼资料包",
            type : 2,
            content : [baseUrl+"/linkageCall/addLinkageCallTask"],
            resize:true,
            maxmin:false,
            isOutAnim:true,
            scrollbar:true,
            area : ['570px','330px'],
            success : function(layero, index){
                // layer.iframeAuto(index);
                var body = layer.getChildFrame('body', index);
               /* if(edit){
                    body.find(".newsName").val(edit.newsName);
                    body.find(".abstract").val(edit.abstract);
                    body.find(".thumbImg").attr("src",edit.newsImg);
                    body.find("#news_content").val(edit.content);
                    body.find(".newsStatus select").val(edit.newsStatus);
                    body.find(".openness input[name='openness'][title='"+edit.newsLook+"']").prop("checked","checked");
                    body.find(".newsTop input[name='newsTop']").prop("checked",edit.newsTop);
                    form.render();
                }*/
            },
             btn: ['保存', '取消'],
             yes: function (index, layero) {
                 var body = layer.getChildFrame('body', index); //得到子页面层的BODY
                 var button = body.find('[lay-submit]'); //获取子窗口表单提交按钮dom
                 button.click();
                 reloadTable();
             }
             , btn2: function (index, layero) {
                 layer.close(index);
             }
        });
        // layer.full(index);
        //改变窗口大小时，重置弹窗的宽高，防止超出可视区域（如F12调出debug的操作）
        /*$(window).on("resize",function(){
            layer.full(index);
        })*/
    }
    $(".addTask_btn").click(function(){
        addTasks();
    });

    //设置外呼号码
    $(".set_callPhone").click(function () {
        //初始时未加载，或者被父级嵌套页面 的localStroge被清除后，再次进入设置号码页面时，需发送号码信息
        var regTxt =/^([0-9]{3,4}-)?[0-9]{7,8}$/ ;
        var regTelPhoneTxt =/^(((13[0-9]{1})|(15[0-9]{1})|(18[0-9]{1}))+\d{8})$/;
        if(targetCallPhone!="" && (regTxt.test(targetCallPhone) || regTelPhoneTxt.test(targetCallPhone))){
            top.postMessage(JSON.stringify({type:"SET",key:"targetPhone",value:targetCallPhone}),'*');
        }
        layer.open({
            title : "设置外呼号码",
            type : 2,
            content : [baseUrl+"/linkageCall/setCallPhone?mainCallPhone="+mainCallPhone+"&targetCallPhone="+targetCallPhone],
            resize:true,
            maxmin:false,
            isOutAnim:true,
            scrollbar:true,
            area : ['570px','330px'],
            btn: ['保存', '取消'],
            yes: function (index, layero) {
                var body = layer.getChildFrame('body', index); //得到子页面层的BODY
                var button = body.find('[lay-submit]'); //获取子窗口表单提交按钮dom
                button.click();
            }
            , btn2: function (index, layero) {
                layer.close(index);
            }
        });
    });
    

    
    //列表操作
    table.on('tool(callTaskList)', function(obj){
        var layEvent = obj.event,
            data = obj.data;
        if(layEvent == 'call'){ //编辑
            if(isCanCall == true){
                console.log(data.status);
                if(data.status == 'FINISHED'){
                    layer.msg("任务包已call完");
                    return;
                }
                if(targetCallPhone == "" || targetCallPhone==null ||  targetCallPhone.toUpperCase()=="NULL"){
                    layer.msg("请先设置call客号码，再进行外呼操作!");
                    return;
                }else{
                    var regTxt =/^([0-9]{3,4}-)?[0-9]{7,8}$/ ;
                    var regTelPhoneTxt =/^(((13[0-9]{1})|(15[0-9]{1})|(18[0-9]{1}))+\d{8})$/;
                    if(targetCallPhone!="" && !regTxt.test(targetCallPhone) && !regTelPhoneTxt.test(targetCallPhone)){
                        layer.msg("请先设置正确的call客号码，再进行外呼操作!");
                        return;
                    }
                }
                var params = "mainCallPhone="+mainCallPhone+"&targetCallPhone="+targetCallPhone+"&taskId="+data.id+"&aiCall=false";
                console.log(params);
                var callWin = layer.open({
                    title : "双呼call客",
                    closeBtn:0,
                    type : 2,
                    content : [baseUrl+"/linkageCall/callDetail?"+params],
                    resize:true,
                    maxmin:false,
                    isOutAnim:true,
                    scrollbar:true,
                    area : ['85%', '93%']/*,
                    btn: ['关闭窗体']
                    , yes: function (index, layero) {
                        var body = layer.getChildFrame('body', index); //得到子页面层的BODY
                        var button = body.find('#closeWin'); //获取子窗口表单提交按钮dom
                        button.click();
                    }*/
                });
                setTimeout(function(){
                    layer.tips('点击关闭，返回上个页面', '.layui-layer-setwin .layui-layer-close', {
                        tips: 3
                    });
                },500);
                layui.layer.full(callWin);
                // layui.layer.full(callWin);freeswitchCall
            }else{
                layer.msg("您当前使用的浏览器版本无法进行云呼操作", {icon: 5});
                return;
            }
        } else if(layEvent=="freeswitchCall"){
            toFreeswitchCall(data);
        }else if(layEvent == 'look'){ //预览
            console.log(data.id);
            var viewCallTaskWin = layer.open({
                title : "查看任务详情",
                type : 2,
                content : [baseUrl+"/linkageCall/viewCallTaskDetail?callTaskId="+data.id],
                area: ['100%', '100%'],
                left:0,
                success : function(layero, index){
                }
            });
            setTimeout(function(){
                layer.tips('点击关闭，返回上个页面', '.layui-layer-setwin .layui-layer-close', {
                    tips: 3
                });
            },500);
            // layer.full(viewCallTaskWin);
        }else if(layEvent == 'arsCall'){//单呼 ==》用于机器人外呼
            if(isCanCall == true) {
                if(data.status == 'FINISHED'){
                    layer.msg("任务包已call完");
                    return;
                }
                if (targetCallPhone == "" || targetCallPhone == null || targetCallPhone.toUpperCase() == "NULL") {
                    layer.msg("请先设置call客号码，再进行外呼操作!");
                    return;
                } else {
                    var regTxt = /^([0-9]{3,4}-)?[0-9]{7,8}$/;
                    var regTelPhoneTxt = /^(((13[0-9]{1})|(15[0-9]{1})|(18[0-9]{1}))+\d{8})$/;
                    if (targetCallPhone != "" && !regTxt.test(targetCallPhone) && !regTelPhoneTxt.test(targetCallPhone)) {
                        layer.msg("请先设置正确的call客号码，再进行外呼操作!");
                        return;
                    }
                }
                var params = "mainCallPhone=" + mainCallPhone + "&targetCallPhone=" + targetCallPhone + "&taskId=" + data.id+"&aiCall=true";
                console.log(params);
                var arsCallWin = layer.open({
                    title: "单呼call客",
                    closeBtn: 0,
                    type: 2,
                    content: [baseUrl + "/linkageCall/callDetail?" + params],
                    resize: true,
                    maxmin: false,
                    isOutAnim: true,
                    scrollbar: true,
                    area : ['85%', '93%']/*,
                    btn: ['关闭窗体']
                    , yes: function (index, layero) {
                        var body = layer.getChildFrame('body', index); //得到子页面层的BODY
                        var button = body.find('#closeWin'); //获取子窗口表单提交按钮dom
                        button.click();
                    }*/
                });
                setTimeout(function(){
                    layer.tips('点击关闭，返回上个页面', '.layui-layer-setwin .layui-layer-close', {
                        tips: 3
                    });
                },500);
                layui.layer.full(arsCallWin);
            }
        }else if(layEvent == 'del'){
            layer.confirm('您确定删除此call客包？',{icon:3, title:'提示信息'},function(index){
                var load = layer.msg('执行中，请稍候',{icon: 16,time:false,shade:0.8});
                $.ajax({
                    type: "POST",
                    url:  baseUrl+'/linkageCall/delCallTask?callTaskId='+data.id,
                    dataType: 'json',
                    success: function (data) {
                        layer.close(load);
                        if(data.code<=0){
                            layer.msg(data.msg);
                            layer.close(index);
                        }else{
                            reloadTable();
                            layer.close(index);
                        }
                    },
                    error: function () {
                        layer.close(load);
                        layer.msg("保存失败");
                        layer.close(index);
                    }
                });
            });
        }
    });


    //选中行时，高亮显示
    function intTableColorChange(){
        $(".layui-table-body tr").click(function(e){
            $(".layui-table-body  tr ").css("background","");
            $(this).css("background","#e6e6e6");
        });
    }

});

function setPhone(mainPhone,targetPhone) {
    localStorage.setItem("targetCallPhone",targetPhone);
    mainCallPhone = mainPhone;
    targetCallPhone = targetPhone;
    console.log("===============postMessage======================");
    top.postMessage(JSON.stringify({type:"SET",key:"targetPhone",value:targetPhone}),'*');
}
